package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.constants.WemediaConstants;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.json.Json;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Resource
    private WmMaterialMapper wmMaterialMapper;

    //内容列表全查
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //判断参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页参数
        dto.checkParam();
        //判断是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //创建分页条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId,user.getId());//根据登录的用户id查询
        queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());//根据文章状态查询
        queryWrapper.like(dto.getKeyword()!=null,WmNews::getTitle,dto.getKeyword());//根据关键字模糊查询
        queryWrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());//根据频道Id查询
        //根据起止时间查询
        queryWrapper.between(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());

        //创建Page对象
        Page pageInfo = new Page(dto.getPage(), dto.getSize());
        //实现分页
        Page page = page(pageInfo, queryWrapper);
        //结果封装
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    //删除文章
    @Override
    public ResponseResult delNews(Integer id) {
        //判断参数
        if (id==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询
        WmNews wmNews = getById(id);
        //判断状态是否已上架
        if (WmNews.Status.PUBLISHED.equals(wmNews.getStatus())){//已上架
            //返回不能删除的信息
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章已上架，请下架后再删除");
        }else {//未上架
            //执行删除并返回结果
            removeById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    /**
     * 文章新增
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //判断参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id
        Integer id = WmThreadLocalUtils.getUser().getId();
        if (id==null){//若id不存在则返回错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
        //将dto中的数据保存到Wm_News
        WmNews wmNews = dto2WmNews(dto,id);
        //执行保存
        save(wmNews);
        //保存文章内容图片和素材之间的关系

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    //保存文章内容图片和素材之间的关系
    public void  saveContentImages(WmNewsDto dto,WmNews wmNews,Integer userId,Integer type){
        //获取文章内容
        String content = dto.getContent();
        //转成Map类型容易取值
        List<Map> maps = JSON.parseArray(content, Map.class);
        //定义一个集合用来存放得到的图片
        ArrayList<String> imageUrl = new ArrayList<>();
        for (Map<String,String> map : maps) {//遍历map集合过滤文本得到图片存入集合中
            if (map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)){
                imageUrl.add(map.get(type));
            }
        }
        //根据图片的url和用户id查询到图片数据
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getUserId,userId);
        queryWrapper.in(WmMaterial::getUrl,imageUrl);
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        //将wmMaterials转成Map集合并遍历得到图片数据的id并存入集合
        Map<String, Integer> collect = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        ArrayList<Integer> materialIds = new ArrayList<>();
        for (String url : imageUrl) {
            Integer materialId = collect.get(url);
            materialIds.add(materialId);
        }
    }



    //将dto中的数据保存到Wm_News表中的方法
    public WmNews dto2WmNews(WmNewsDto dto,Integer userId){
        WmNews wmNews = new WmNews();
        wmNews.setChannelId(dto.getChannelId());
        wmNews.setContent(dto.getContent());
        wmNews.setCreatedTime(new Date());
        wmNews.setLabels(dto.getLabels());
        wmNews.setTitle(dto.getTitle());
        wmNews.setType(dto.getStatus());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(userId);
        //获取封面图片并保存到wm_news中
        String imageStr = dto.getImages().toString();
        //判断imageStr是否为null
        if (imageStr!=null&&imageStr.length()>0){
            //不为空则说明文章封面不是无图或自动
            //字符串替换掉多余的字符
            String newImages = imageStr.replace("[", "").replace("]", "").replace(" ", "").trim();
            wmNews.setImages(newImages);
        }
        return wmNews;
    }


}
